package com.http.form;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class Form {
	
	private String method = "post";
	
	private String action = "";
	
	private ArrayList<NameValuePair> NameValuePairs = new ArrayList<NameValuePair>();
	
	private String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1";

	private int timeout=30000;
	
	private String charset = "utf-8";
	
	private String responseBody = "";
	
	private String vCode = "";
	
	public ArrayList<String[]> requestHeaders = new ArrayList<String[]>();
	
	private HttpClient httpClient = new HttpClient();
	
	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}


	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	


	public void pushNameValuePair(String name,String value) {
		NameValuePair mp  = new NameValuePair(name , value);
		NameValuePairs.add(mp);
	}
	
	public NameValuePair[] getNameValuePairs(){
		int size = this.NameValuePairs.size();
		NameValuePair[] mvps = new NameValuePair[size];
		
		for(int i=0; i < size ;i++){
			mvps[i] = (NameValuePair)this.NameValuePairs.get(i);
		}
		
		return mvps;
	}

	public String getUserAgent() {
		return userAgent;
	}

	public void setUserAgent(String userAgent) {
		this.userAgent = userAgent;
	}
	
	public void setRequestHeader(String name, String value){
		String[] str = {name, value};
		this.requestHeaders.add(str);
	}
	
	public void displayCookies(){
		//查看cookie信息

        CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
       // cookiespec.match(arg0, arg1, arg2, arg3, arg4)
        //String host = this.action.substring(0,34);
        Cookie[] cookies = cookiespec.match("LOGON_SITE", 80, "/", false, this.httpClient.getState().getCookies());

       if (cookies.length == 0) {

           System.out.println("None");   

       } else {

           for (int i = 0; i < cookies.length; i++) {

               System.out.println(cookies[i].toString());   

           }

       }
	}
	
	public void sendAsPostMethod() {
		   
			httpClient.setConnectionTimeout(this.getTimeout());  
		     //client.getHostConfiguration().setHost("172.16.1.33", 6100, "http");     
			
		     PostMethod postMethod = new PostMethod(this.getAction());  
		     postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, this.getCharset());  
		     postMethod.setRequestHeader("user-agent", this.getUserAgent());
		     for(int i =0; i < this.requestHeaders.size();i++){
		    	 String[] strA = this.requestHeaders.get(i);
		    	 postMethod.setRequestHeader(strA[0],strA[1]);
		     }
		     
		     NameValuePair[] data = getNameValuePairs();
		 
		
		     postMethod.setRequestBody(data);  
		     try {
		    	 httpClient.executeMethod(postMethod);
				this.responseBody = postMethod.getResponseBodyAsString();
			} catch (HttpException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		     
		   
		
			
			postMethod.releaseConnection();  
	}
	
	public String getResponseBody() {
		return responseBody;
	}

	public void setResponseBody(String responseBody) {
		this.responseBody = responseBody;
	}

	public void sendAsGetMethod(){
	
		GetMethod getMethod = new GetMethod(this.getAction());
		httpClient.setConnectionTimeout(this.getTimeout());  
	    
	     getMethod.setRequestHeader("user-agent", this.getUserAgent());
	     getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, this.getCharset());
	     for(int i =0; i < this.requestHeaders.size();i++){
	    	 String[] strA = this.requestHeaders.get(i);
	    	 getMethod.setRequestHeader(strA[0],strA[1]);
	     }

	     NameValuePair[] data = this.getNameValuePairs();
	     getMethod.setQueryString(data);
	     this.responseBody = "";
	    try {
	    	 httpClient.executeMethod(getMethod);
		} catch (HttpException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			this.responseBody = (String) getMethod.getResponseBodyAsString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		
		getMethod.releaseConnection();
			
			
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}
	
	/**
	 * 读取验证码
	 * @return
	 */
	public String getVCode(){
		return this.vCode;
	}
	
	/**
	 * 手写输入验证码
	 */
	public void readInVCode(){
		   try{
			   		//在Java当中，用户输入要通过InputStream(输入流)来获取。
			   		//System.in就是系统的输入流。缺省情况下这个输入流连接到控制台(命令行)。
			   		//InputStreamReader就是用来读取InputStream的类。
			   		System.out.println("请输入验证码：");
			   		InputStreamReader is_reader=new InputStreamReader(System.in);
			   		//通常使用BufferedReader来读取InputStream中的字符串内容。
			   		//BufferedReader可以一次读取一行。
			   		String str=new BufferedReader(is_reader).readLine();
			   		//将读取的字符串输出到屏幕上。
			   		str = str.trim();
			   		this.vCode = str;
			   		System.out.println("您输入的是："+str);
		   }catch(IOException e){
			   e.printStackTrace();
		   }
	   }
	
	/**
	 * 下载文件
	 * @param src
	 * @param dst
	 */
	public void downloadByUrl(String src, String dst)
	   {

	     //创建GET方法的实例
	     GetMethod getMethod = new GetMethod(src);
	     //GetMethod getMethod = new GetMethod("http://10.164.80.52/dav/5000/moban.rar");
	     //使用系统提供的默认的恢复策略
	     getMethod.setRequestHeader("user-agent", this.getUserAgent());
	     getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
	     try
	     {
	         //执行getMethod
	         int statusCode = httpClient.executeMethod(getMethod);
	         if (statusCode != HttpStatus.SC_OK)
	         {
	             System.err.println("Method failed: " + getMethod.getStatusLine());
	         }
	         //读取内容
	         byte[] responseBody = getMethod.getResponseBody();
	        
	        
	         String serverfile = dst;
	         //String serverfile = "d:\\moban.rar";
	         OutputStream serverout = new FileOutputStream(serverfile);
	        
	         serverout.write(responseBody);   
	         serverout.flush();   
	         serverout.close();   

	         //处理内容
	         //System.out.println(new String(responseBody));
	         System.out.println("OK!");
	     }
	     catch (HttpException e)
	     {
	         //发生致命的异常，可能是协议不对或者返回的内容有问题
	         System.out.println("Please check your provided http address!");
	         e.printStackTrace();
	     }
	     catch (IOException e)
	     {
	         //发生网络异常
	         e.printStackTrace();
	     }
	     finally
	     {
	         //释放连接
	         getMethod.releaseConnection();
	     }
	   }
	
}
